package com.platform.manager.action.system;

import com.platform.common.mybatis.Page;
import com.platform.common.mybatis.context.ContextHolder;
import com.platform.common.util.JsonUtil;
import com.platform.domain.model.Role;
import com.platform.domain.result.DataGirdData;
import com.platform.domain.result.ResultData;
import com.platform.domain.result.TreeGridData;
import com.platform.manager.action.BaseAction;
import com.platform.manager.action.common.Constants;
import com.platform.service.RoleService;
import org.apache.struts2.convention.annotation.*;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-18
 * Time: 下午2:31
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/system")
@Service("roleAction")
@ParentPackage("jsonPackage")
public class RoleAction extends BaseAction {

    @Resource
    private RoleService roleService;

    private List<Role> roles;

    private List<Role> notRoles;

    private String userId;

    private Role role;

    /**
     * 查询用户信息列表
     *
     * @return
     */
    @Action(value = "queryRoles", interceptorRefs = @InterceptorRef("pageStack"),
            results = {@Result(name = "success", type = "json", params = {"root", "dataGirdData"})})
    public String queryRoles() {
        try {
            if (role != null) {
                logger.info("");
            }
            // 查询符合条件的用户列表
            List<Role> list = roleService.select(null);
            dataGirdData = new DataGirdData();
            dataGirdData.setRows(list);
            // 获取翻页参数
            Page page = ContextHolder.getPage();
            dataGirdData.setTotal(page.getTotalResult());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }


    /**
     * 保存用户信息列表
     *
     * @return
     */
    @Action(value = "saveRoles", results = {@Result(name = "success", type = "json", params = {"root", "result"})})
    public String saveRoles() {
        try {
            if (jsonStr != null) {
                print("前台发送的JSON数据：" + jsonStr);
                Map<String, List> maps = JsonUtil.jsonToMap(jsonStr, Role.class);
                List inserted = maps.get("inserted");
                List updated = maps.get("updated");
                List deleted = maps.get("deleted");

                // 保存未插入、更新、删除成功的的用户登录名
                StringBuffer buffer = new StringBuffer();

                if (inserted != null) {
                    for(Object obj : inserted){
                        Role role = (Role) obj;
                        int resInt = roleService.insert(role);
                        if (resInt != 1) {
                            buffer.append(" [").append(role.getRoleId()).append("]");
                        }
                    }
                }

                if (updated != null) {
                    for(Object obj : updated){
                        Role role = (Role) obj;
                        int resInt = roleService.update(role);
                        if (resInt != 1) {
                            buffer.append(" [").append(role.getRoleId()).append("]");
                        }
                    }
                }

                if (deleted != null) {
                    for(Object obj : deleted){
                        Role role = (Role) obj;
                        int resInt = roleService.delete(role);
                        if (resInt != 1) {
                            buffer.append(" [").append(role.getRoleId()).append("]");
                        }
                    }
                }


                result = new ResultData();
                if (buffer.length() == 0) {
                    result.setSuccess(true);
                    result.setMessage("操作成功！");
                } else {
                    result.setSuccess(false);
                    result.setMessage("操作失败！\n以下角色操作失败！\n[角色ID]：" + buffer.toString());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户角色权限列表
     *
     * @return
     */
    @Action(value = "queryUserRoles", results = {@Result(name = "success", type = "json", params = {"root", "treeGridDatas"})})
    public String queryUserRoles() {
        try {
            if (userId != null) {
                logger.info(userId);
            }
            // 查询符合条件的记录总数
            roles = roleService.selectByUserId(userId);

            if (roles != null) {
                treeGridDatas = new ArrayList<TreeGridData>();
                for (Role role : roles) {
                    TreeGridData data = new TreeGridData();
                    data.setId(role.getRoleId());
                    data.setText(role.getRoleName());
                    data.setState("closed");
                    treeGridDatas.add(data);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户角色权限列表
     *
     * @return
     */
    @Action(value = "editUserRoles", results = {@Result(name = "success", location = "/system/user/user_role.jsp")})
    public String editUserRoles() {
        try {
            // 已经授权的角色集合
            roles = roleService.selectByUserId(userId);
            // 未授权的角色集合
            notRoles = roleService.selectByNotUserId(userId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户角色权限列表
     *
     * @return
     */
    @Action(value = "queryByUserRoles", results = {@Result(name = "success", type = "json", params = {"root", "roles"})})
    public String queryByUserRoles() {
        try {
            // 已经授权的角色集合
            roles = roleService.selectByUserId(userId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户角色权限列表
     *
     * @return
     */
    @Action(value = "queryByNotUserRoles", results = {@Result(name = "success", type = "json", params = {"root", "notRoles"})})
    public String queryByNotUserRoles() {
        try {
            // 未授权的角色集合
            notRoles = roleService.selectByNotUserId(userId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户信息列表
     *
     * @return
     */
    @Action(value = "saveRoleFunctions", results = {@Result(name = "success", type = "json",
            params = {"root", "result", "contentType", "text/html"})})
    public String saveRoleFunctions() {
        try {
            int resultInt = roleService.insertRoleFunctions(role);
            // 返回执行结果
            result = new ResultData();
            if (resultInt > 0) {
                result.setSuccess(true);
                result.setMessage("修改成功！");
            } else {
                result.setSuccess(false);
                result.setMessage("修改失败！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    @JSON
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @JSON
    public List<Role> getNotRoles() {
        return notRoles;
    }

    public void setNotRoles(List<Role> notRoles) {
        this.notRoles = notRoles;
    }
}
